<template name="components">
	<view>
		<view class="UCenter-bg">
			<view class="solid-bottom text-xl" style="text-align: center;">
				<text class="text-white text-bold">RPCC</text>
			</view>
			<view class="margin-top-sm" style="text-align: center;">
			  <text>量化交易机器人程序控制台</text>
			</view>
			<view class="margin-top-sm" style="text-align: center;">
			  <text>{{ showFormEmail }}</text>
			</view>
			<image src="/static/wave.gif" mode="scaleToFill" class="response gif-wave"></image>
		</view>
		
		<!-- 选项卡 -->
		<tab :list="strategy" :tabcur="TabCur" @tab="tab" @email="email"></tab>
		
		<!-- 列表 -->
		<view class="nav-list margin-top-xl">
			<navigator v-if="item.strategy_name === TabCur" hover-class='none' 
			:url="`/pages_${item.strategy_name}/${item.strategy_name}?strategy_name=${item.strategy_name}&exchange_url=${item.exchange_url}&exchange_domain=${item.exchange_domain}&exchange_name=${item.exchange_name}&color=${item.color}`" 
			class="nav-li" navigateTo :class="'bg-'+item.color" :style="[{animation: 'show ' + ((index+1)*0.2+1) + 's 1'}]" v-for="(item,index) in elements" :key="index">
				<span class="nav-title">{{item.exchange_name}}</span>
				<span>{{item.strategy_name}}</span>
				<view class="nav-name">{{item.exchange_url}}</view>
			</navigator>
		</view>
		
		<!-- 邮箱弹出框 -->
		<view class="cu-modal bottom-modal" :class="modalEmail?'show':''">
			<view class="cu-dialog" style="background-color: #ffffff;">
				<view class="cu-bar bg-white">
					<view class="action text-green" @click="submitEmail">确定</view>
					<view class="action text-blue" @tap="modalEmail = false">取消</view>
				</view>
				<view class="cu-form-group" style="margin-bottom: 20px;">
					<view class="title">邮件地址</view>
					<input placeholder="用于接收交易机器人程序错误信息" v-model="formEmail" style="text-align: left;"></input>
				</view>
			</view>
		</view>
		
		<!-- 更新机器人邮件失败的提示弹出框 -->
		<view class="cu-modal" :class="modalMsg?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">机器人邮件更新失败提示</view>
					<view class="action" @tap="modalMsg=false">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl">
					<view v-for="(value, index) in emailMsg" :key="index" class="text-lg padding">
						<text class="text-black">{{ value }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import tab from '@/components/tab/tab.vue'
	import { login, updateEmail } from '@/api/basic/basic.js'
	export default {
		components: {
			tab, 
		},
		data() {
			return {
				strategy: [],
				TabCur: '',
				elements: [],
				modalEmail: false,
				formEmail: '',
				showFormEmail: '',
				modalMsg: false,
				emailMsg: []
			};
		},
		onLoad() {
			var _this = this
			_this.get_strategy_name()
			uni.getStorage({
				key:'email',
				success(res) {
					_this.showFormEmail = res.data
				},
				fail() {
					_this.showFormEmail = ''
				}
			})
		},
		methods: {
			tab(data) {
				this.TabCur = data.data
			},
			email() {
				console.log('点击了设置邮件.')
				this.modalEmail = true
			},
			// 提交邮件
			submitEmail() {
				var _this = this
				
				if (_this.formEmail === '') {
					uni.showToast({ icon: 'none', title: '邮件地址不能为空' })
					return
				}
				
				if (_this.isEmail(_this.formEmail) === false) {
					uni.showToast({ icon: 'none', title: '邮件地址格式错误' })
					return
				}
				
				uni.getStorage({
					key:'openId',
					success(openIdRes) {
						console.log('获取到了openId缓存', openIdRes.data)
						uniCloud.callFunction({
							name:'update_email',
							data:{
								openid: openIdRes.data,
								email: _this.formEmail
							},
							success(updateRes) {
								console.log('更新云函数邮件地址', updateRes.result)
								_this.modalEmail = false
								uni.showToast({ icon: 'none', title: updateRes.result.msg })
								
								uni.setStorage({
									key:'email',
									data:_this.formEmail,
									success() {
										_this.showFormEmail = _this.formEmail
										setTimeout(function () {
											console.log('循环更新Api程序邮件')
											_this.updateApiEmail(openIdRes.data, _this.formEmail)
										}, 2000);
									},
									fail(setEmailRee) {
										uni.showToast({ icon: 'none', title: `邮件缓存失败: ${setEmailRee.errMsg}` })
									}
								})
							},
							fail(updateErr) {
								uni.showToast({ icon: 'none', title: `邮件更新云函数失败: ${updateErr.errMsg}` })
							}
						})
					},
					fail(openIdErr) {
						console.log('邮件提交获取openId失败', openIdErr.errMsg)
						uni.showToast({ icon: 'none', title: `邮件提交获取openId失败: ${openIdErr.errMsg}` })
					},
					complete() {
						setTimeout(function () {
							uni.hideLoading();
						}, 2000);
					}
				})
			},
			// 获取首页基础数据
			get_strategy_name() {
				uni.showLoading({
					title: '加载中...',
				})
				var that = this
				uni.getStorage({
					key:'openId',
					success(getHomeRes) {
						uniCloud.callFunction({
							name:'get_home',
							data:{
								openid:getHomeRes.data
							},
							success(res) {
								uni.setStorage({
									key:'email',
									data:res.result.data.email,
									fail(setEmailRee) {
										uni.showToast({ icon: 'none', title: `邮件缓存失败: ${setEmailRee.errMsg}` })
									}
								})
								console.log('缓存的邮件地址: ', res.result.data.email)
								
								that.strategy = res.result.data.strategy
								var exchange = res.result.data.exchange
								for (let i = 0; i < that.strategy.length; i++) {
									for (let j = 0; j < exchange.length; j++) {
										that.elements.unshift({
											"strategy_name": that.strategy[i].name,
											"exchange_url": exchange[j].exchange_url,
											"exchange_domain": exchange[j].exchange_domain,
											"exchange_name": exchange[j].exchange_name,
											"color": exchange[j].color
										})
									}
								}
								that.TabCur = that.strategy[0].name
							},
							fail(err) {
								uni.showToast({ icon: 'none', title: `获取交易所与策略数据失败: ${err.errMsg}` })
							}, complete: () => {
								// 隐藏loadings
								uni.hideLoading()
							}
						})
					},
					fail(getHomeErr) {
						uni.showToast({ icon: 'none', title: `Home获取openId失败: ${getHomeErr.errMsg}` })
					}
				})
			},
			// 更新机器人邮件地址
			updateApiEmail (openId, formEmail) {
				var _this = this
				console.log('根据openId:' + openId + '获取云数据库的config数据')
				// 判断存在接口数据时，循环登录Api并更新邮件
				uniCloud.callFunction({
					name:'get_openId_config',
					data:{ open_id:openId },
					success(configRes) {
						console.log('config配置获取成功', configRes.result.data)
						if (configRes.result.data.length === 0) {
							return
						}
						
						uni.showLoading({ title: '正在更新机器人邮件地址...' })
						configRes.result.data.forEach(function (item, index) {
							
							login(item.ip_address, {
								'username':item.username, 'password':item.password
							}).then(res =>{
								console.log('config登录回调', res)
								if (res.data.access) {
									uni.setStorage({
										key:item.exchange_domain + item.strategy_name,
										data:res.data,
										fail() {
											uni.showToast({ title: 'token缓存失败' })
										}
									})
									console.log('更新'+item.exchange_domain+'的'+item.strategy_name+'邮件')
									updateEmail(item.ip_address, res.data.access, {address: _this.formEmail}).catch(err => {
										_this.showEmailModal(item)
									})
									
								} else {
									_this.showEmailModal(item)
								}
							}).catch(err => {
								_this.showEmailModal(item)
							})
							
						})
					},
					fail(configErr) {
						uni.showToast({ icon: 'none', title: `config配置获取失败: ${configErr.errMsg}` })
					}
				})
			},
			// 连接到机器人错误的提示弹窗
			showEmailModal(item) {
				this.emailMsg.push(item.exchange_domain+'['+item.strategy_name+']'+' ['+item.ip_address+']')
				setTimeout(function () {
					uni.hideLoading();
				}, 2000);
				this.modalMsg = true
			},
			// 检测是否为邮件
			isEmail(email) {
			  var reg = /^[A-Za-z0-9]+[A-Za-z0-9_.-]*@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.[A-Za-z0-9_-]+$/;
			  return reg.test(email);
			}
		}
	}
</script>

<style>
	
	.navLi {
		width: 100%;
	}
	
	span {
	    display: inline-block;
	    width: 50%;
	}
	
	span:first-of-type {
		font-weight: bold;
	    text-align: left; 
	}
	
	span:last-of-type {
	    text-align: right;
	} 
	
	.UCenter-bg {
	  background-image: url('../../static/index.jpg');
	  background-size: cover;
	  height: 550rpx;
	  display: flex;
	  justify-content: center;
	  padding-top: 40rpx;
	  overflow: hidden;
	  position: relative;
	  flex-direction: column;
	  align-items: center;
	  color: #fff;
	  font-weight: 300;
	  text-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
	}
	
	.UCenter-bg text {
	  opacity: 0.8;
	}
	
	.UCenter-bg image {
	  width: 200rpx;
	  height: 200rpx;
	}
	
	.UCenter-bg .gif-wave{
	  position: absolute;
	  width: 100%;
	  bottom: 0;
	  left: 0;
	  z-index: 99;
	  mix-blend-mode: screen;  
	  height: 100rpx;   
	}
</style>
